package com.example.rabbit.service;


import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 消息发送者
 */
@Component
public class Sender {

    @Autowired
    private  AmqpTemplate amqpTemplate;

    /**
     * 发送消息的方法
     * @param queueName 队列名称
     * @param msg  消息内容
     */
    public  void send (String queueName, String msg){
        amqpTemplate.convertAndSend(queueName,msg);
    }

    public  void send (String queueName, Object msg){
        amqpTemplate.convertAndSend(queueName,msg);
    }
    /**
     * 发送消息的方法
     * @param queueName 队列名称
     * @param msg  消息内容
     */
    public  void sendByDDL (String exchange,String routingkey, String msg,long time){
        amqpTemplate.convertAndSend(exchange,routingkey,msg, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                //给消息设置延迟毫秒值
                message.getMessageProperties().setExpiration(String.valueOf(time));
                return message;
            }
        });
    }

    /**
     * 发送消息的方法
     * @param exchange 交换器名称
     * @param routingkey 路由键
     * @param msg 消息
     */
    public void send(String exchange,String routingkey, String msg){
        this.amqpTemplate.convertAndSend(exchange, routingkey, msg);
    }
}
